import socket
import threading
import time
import random
'''
net.Server(threading.Threading)\r\n
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n
WSocket服务端监听程序\r\n
'''
class Server(threading.Thread):  
    
    def __init__(self,address,listen=100):  
        '''
        Feature\r\n
            __init__(self,address,listen)\r\n
        Description\r\n
            初始化\r\n
        Args\r\n
            address\r\n
                type:ip address ("127.0.0.1",3000)\r\n
                description:IP地址与端口\r\n
            listen\r\n
                type:int\r\n
                default:100\r\n
                description:监听数量\r\n
        '''
        threading.Thread.__init__(self) #初始化父类Thread  
        self._flag=threading.Event()
        self._flag.set()
        self._runing=threading.Event()
        self._runing.set()
        self.socket = None              #socket
        self.s_address=address          #address
        self.s_listen=listen            #listen number
        self.connectNum=0               #connect number
        self.classname=None             #request process
        self.namespace=None             #request namespace
        self.method=None                #request process runtime method

    def configRequest(self,_namespace,_classname,_method):
        '''
        Feature\r\n
            configRequest(self,_namespace,_classname,_method)\r\n
        Description\r\n
            配置client处理线程\r\n
        Args\r\n
            _namespace\r\n
                type:string\r\n
                description:命名空间\r\n
            _classname\r\n
                type:string\r\n
                description:类名\r\n
            _method\r\n
                type:string\r\n
                description:处理方法\r\n
        '''
        self.namespace=_namespace
        self.classname=_classname
        self.method=_method

    def run(self):
        '''
        Feature\r\n
            run(self)\r\n
        Description\r\n
            处理线程\r\n
        '''  
        try:  
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
            self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  
            self.socket.bind(self.s_address)  
            self.socket.listen(self.s_listen)
            
        except Exception as e:
            return False,e;
        try:  
            while self._runing.is_set():
                self._flag.wait()
                connection, address = self.socket.accept()
                if connection:
                    handle=__import__(self.namespace+"."+self.classname,fromlist=(True))
                    if handle:
                        if hasattr(handle,self.classname):
                            func=getattr(handle,self.classname)
                            if func:
                                newSocket=func(connection,address,self.connectNum,self.clients)
                                if newSocket:
                                    if hasattr(newSocket,self.method):    #检查是否有方法
                                        run=getattr(newSocket,self.method)
                                        if run:
                                            self.clients[self.connectNum]=run
                                            self.clients[self.connectNum]()
                                            self.connectNum = self.connectNum + 1
                                    else:
                                        print("Server - has error Don't found method run!")
                                else:
                                    print("Server - Create object {0}.{1} Fail!".format(self.namespace,self.classname))
                        else:
                            print("Server -  has error Don't found class {0}!".format(self.classname))
                    else:
                        print("Server - has error Don't import madule(%s.%s)" % (self.namespace,self.classname))
        except Exception as e:
            print(e)
            self._flag.set()
            self._runing.clear()
        finally:
            print("Server - close server")
            self.socket.shutdown(2)
            self.socket.close()

    def stop(self):
        for o in self.clients:
            o.stop()
        self._flag.clear()

    def resume(self):
        for o in self.clients:
            o.resume()
        self._flag.set()

    def close(self):
        for o in self.clients:
            o.close()
        self._flag.set()
        self._runing.clear()